import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

// 创建回答
export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { id: questionId } = params
    const { content } = await req.json()

    // 验证输入
    if (!content) {
      return NextResponse.json(
        { message: '回答内容不能为空' },
        { status: 400 }
      )
    }

    // 检查问题是否存在
    const question = await prisma.forumQuestion.findUnique({
      where: { id: questionId },
    })

    if (!question) {
      return NextResponse.json(
        { message: '问题不存在' },
        { status: 404 }
      )
    }

    // 创建回答
    const answer = await prisma.forumAnswer.create({
      data: {
        content,
        authorId: session.user.id,
        questionId,
      },
      include: {
        author: {
          select: {
            id: true,
            name: true,
            role: true,
          },
        },
      },
    })

    return NextResponse.json({
      message: '回答发布成功',
      answer,
    }, { status: 201 })
  } catch (error) {
    console.error('创建回答失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
} 